package com.njtoyo.taxi.admin.utils.private_number.report;

import com.njtoyo.taxi.admin.utils.private_number.PrivateNumberClient;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Objects;

@Slf4j
public class PrivateNumberAesHelper {

    private static final String KEY = PrivateNumberClient.APP_SECRET;

    /**
     * 生成 AES-128 密钥（16字节）
     */
    public static SecretKey generateKey(String key) {
        if(Objects.isNull(key)|| key.isEmpty()){
            return null;
        }
        StringBuilder aseKey= new StringBuilder();
        for(int i = 0 ; i < 16 ; i++){
            aseKey.append(key.charAt(i % key.length()));
        }
        return new SecretKeySpec(aseKey.toString().getBytes(),"AES");
    }


    /**
     * 加密（返回 Base64 字符串）
     */
    public static String encrypt(String plaintext, String key) throws Exception {
        SecretKey secretKey =  generateKey(key);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] cipherBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(cipherBytes);
    }

    /**
     * 解密（输入 Base64 字符串）
     */
    public static String decrypt(String ciphertext, String key) throws Exception {
        SecretKey secretKey =  generateKey(key);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] cipherBytes = Base64.getDecoder().decode(ciphertext);
        return new String(cipher.doFinal(cipherBytes), StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        try {
            // 1. 生成密钥
            String key =  "abcd1234567890";
            String originalText = "hello,AES加密原文";
            // 2. 加密
            String encryptedText = encrypt(originalText, key);
            System.out.println("加密结果: " + encryptedText); // 示例输出: 5V8Z6L... (每次不同)
            // 3. 解密
            String decryptedText = decrypt(encryptedText, key);
            System.out.println("解密结果: " + decryptedText); // 应与原文字符一致

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SneakyThrows
    public static String encryptBase64(String text) {
        return encrypt(text,KEY);
    }

}
